home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1995 November / EnigmA AMIGA RUN 02 (1995)(G.R. Edizioni)(IT)[!][issue 1995-11][Skylink CD].iso / earcd / util / arcer / gnutar10.lha / GnuTAR / GNUTarSource.LHA / source / buffer.c < prev    next >
C/C++ Source or Header  |  1991-07-04  |  30KB  |  1,331 lines

  1. /* Buffer management for tar.
  2.    Copyright (C) 1988 Free Software Foundation
  3.  
  4. This file is part of GNU Tar.
  5.  
  6. GNU Tar is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 1, or (at your option)
  9. any later version.
  10.  
  11. GNU Tar is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Tar; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /*
  21.  * Buffer management for tar.
  22.  *
  23.  * Written by John Gilmore, ihnp4!hoptoad!gnu, on 25 August 1985.
  24.  *
  25.  * @(#) buffer.c 1.28 11/6/87 - gnu
  26.  */
  27.  
  28. #include <stdio.h>
  29. #include <errno.h>
  30. #include <sys/types.h>        /* For non-Berkeley systems */
  31. #include <sys/stat.h>
  32. #include <signal.h>
  33.  
  34. #if !defined(MSDOS) && !defined(AMIGA)
  35. #include <sys/ioctl.h>
  36. #if !defined(USG) || defined(HAVE_MTIO)
  37. #include <sys/mtio.h>
  38. #endif
  39. #endif
  40.  
  41. #ifdef    MSDOS
  42. # include <fcntl.h>
  43. #include <process.h>
  44. #else
  45. # ifdef XENIX
  46. #  include <sys/inode.h>
  47. # endif
  48. # include <sys/file.h>
  49. #endif
  50.  
  51. extern int errno;
  52.  
  53. #include "tar.h"
  54. #include "port.h"
  55. #include "rmt.h"
  56.  
  57. /* Either stdout or stderr:  The thing we write messages (standard msgs, not
  58.    errors) to.    Stdout unless we're writing a pipe, in which case stderr */
  59. FILE *msg_file = stdout;
  60.  
  61. #define STDIN    0        /* Standard input  file descriptor */
  62. #define STDOUT    1        /* Standard output file descriptor */
  63.  
  64. #define PREAD    0        /* Read  file descriptor from pipe() */
  65. #define PWRITE    1        /* Write file descriptor from pipe() */
  66.  
  67. #ifdef __STDC__
  68. extern void    *malloc();
  69. extern void    *valloc();
  70. #else
  71. extern char    *malloc();
  72. extern char    *valloc();
  73. #endif
  74. #ifndef AMIGA
  75. extern time_t time();
  76. #endif
  77.  
  78. extern char    *index(), *strcat();
  79. extern char    *strcpy();
  80.  
  81. /*
  82.  * V7 doesn't have a #define for this.
  83.  */
  84. #ifndef O_RDONLY
  85. #define O_RDONLY    0
  86. #endif
  87. #ifndef O_RDWR
  88. #define O_RDWR        2
  89. #endif
  90. #ifndef O_CREAT
  91. #define O_CREAT     0
  92. #endif
  93. #ifndef O_BINARY
  94. #define O_BINARY    0
  95. #endif
  96.  
  97. #define MAGIC_STAT    105    /* Magic status returned by child, if
  98.                    it can't exec.  We hope compress/sh
  99.                    never return this status! */
  100.  
  101. void writeerror();
  102. void readerror();
  103.  
  104. void ck_pipe();
  105. void ck_close();
  106.  
  107. extern void finish_header();
  108. extern void to_oct();
  109.  
  110. /* Obnoxious test to see if dimwit is trying to dump the archive */
  111. dev_t ar_dev;
  112. ino_t ar_ino;
  113.  
  114. /*
  115.  * The record pointed to by save_rec should not be overlaid
  116.  * when reading in a new tape block.  Copy it to record_save_area first, and
  117.  * change the pointer in *save_rec to point to record_save_area.
  118.  * Saved_recno records the record number at the time of the save.
  119.  * This is used by annofile() to print the record number of a file's
  120.  * header record.
  121.  */
  122. static union record **save_rec;
  123.  union record record_save_area;
  124. static long        saved_recno;
  125.  
  126. /*
  127.  * PID of child program, if f_compress or remote archive access.
  128.  */
  129. static int    childpid = 0;
  130.  
  131. /*
  132.  * Record number of the start of this block of records
  133.  */
  134. long    baserec;
  135.  
  136. /*
  137.  * Error recovery stuff
  138.  */
  139. static int    r_error_count;
  140.  
  141. /*
  142.  * Have we hit EOF yet?
  143.  */
  144. static int    eof;
  145.  
  146. /* JF we're reading, but we just read the last record and its time to update */
  147. extern time_to_start_writing;
  148. int file_to_switch_to= -1;    /* If remote update, close archive, and use
  149.                    this descriptor to write to */
  150.  
  151. static int volno = 1;        /* JF which volume of a multi-volume tape
  152.                    we're on */
  153.  
  154. char *save_name = 0;        /* Name of the file we are currently writing */
  155. long save_totsize;        /* total size of file we are writing.  Only
  156.                    valid if save_name is non_zero */
  157. long save_sizeleft;        /* Where we are in the file we are writing.
  158.                    Only valid if save_name is non-zero */
  159.  
  160. int write_archive_to_stdout;
  161.  
  162. /* Used by fl_read and fl_write to store the real info about saved names */
  163. static char real_s_name[NAMSIZ];
  164. static long real_s_totsize;
  165. static long real_s_sizeleft;
  166.  
  167. /* Reset the EOF flag (if set), and re-set ar_record, etc */
  168.  
  169. void
  170. reset_eof()
  171. {
  172.     if(eof) {
  173.         eof=0;
  174.         ar_record=ar_block;
  175.         ar_last=ar_block+blocking;
  176.         ar_reading=0;
  177.     }
  178. }
  179.  
  180. /*
  181.  * Return the location of the next available input or output record.
  182.  * Return NULL for EOF.  Once we have returned NULL, we just keep returning
  183.  * it, to avoid accidentally going on to the next file on the "tape".
  184.  */
  185. union record *
  186. findrec()
  187. {
  188.     if (ar_record == ar_last) {
  189.         if (eof)
  190.             return (union record *)NULL;    /* EOF */
  191.         flush_archive();
  192.         if (ar_record == ar_last) {
  193.             eof++;
  194.             return (union record *)NULL;    /* EOF */
  195.         }
  196.     }
  197.     return ar_record;
  198. }
  199.  
  200.  
  201. /*
  202.  * Indicate that we have used all records up thru the argument.
  203.  * (should the arg have an off-by-1? XXX FIXME)
  204.  */
  205. void
  206. userec(rec)
  207.     union record *rec;
  208. {
  209.     while(rec >= ar_record)
  210.         ar_record++;
  211.     /*
  212.      * Do NOT flush the archive here.  If we do, the same
  213.      * argument to userec() could mean the next record (if the
  214.      * input block is exactly one record long), which is not what
  215.      * is intended.
  216.      */
  217.     if (ar_record > ar_last)
  218.         abort();
  219. }
  220.  
  221.  
  222. /*
  223.  * Return a pointer to the end of the current records buffer.
  224.  * All the space between findrec() and endofrecs() is available
  225.  * for filling with data, or taking data from.
  226.  */
  227. union record *
  228. endofrecs()
  229. {
  230.     return ar_last;
  231. }
  232.  
  233.  
  234. /*
  235.  * Duplicate a file descriptor into a certain slot.
  236.  * Equivalent to BSD "dup2" with error reporting.
  237.  */
  238. void
  239. dupto(from, to, msg)
  240.     int from, to;
  241.     char *msg;
  242. {
  243.     int err;
  244.  
  245.     if (from != to) {
  246.         err=close(to);
  247.         if(err<0 && errno!=EBADF) {
  248.             msg_perror("Cannot close descriptor %d",to);
  249.             exit(EX_SYSTEM);
  250.         }
  251.         err = dup(from);
  252.         if (err != to) {
  253.             msg_perror("cannot dup %s",msg);
  254.             exit(EX_SYSTEM);
  255.         }
  256.         ck_close(from);
  257.     }
  258. }
  259.  
  260. #ifdef MSDOS
  261. void
  262. child_open()
  263. {
  264.     fprintf(stderr,"MSDOS %s can't use compressed or remote archives\n",tar);
  265.     exit(EX_ARGSBAD);
  266. }
  267. #else
  268. void
  269. child_open()
  270. {
  271.     int pipe[2];
  272.     int err = 0;
  273.  
  274.     int kidpipe[2];
  275.     int kidchildpid;
  276.  
  277. #define READ    0
  278. #define WRITE    1
  279.  
  280.     ck_pipe(pipe);
  281.  
  282.     childpid=fork();
  283.     if(childpid<0) {
  284.         msg_perror("cannot fork");
  285.         exit(EX_SYSTEM);
  286.     }
  287.     if(childpid>0) {
  288.         /* We're the parent.  Clean up and be happy */
  289.         /* This, at least, is easy */
  290.  
  291.         if(ar_reading) {
  292.             f_reblock++;
  293.             archive=pipe[READ];
  294.             ck_close(pipe[WRITE]);
  295.         } else {
  296.             archive = pipe[WRITE];
  297.             ck_close(pipe[READ]);
  298.         }
  299.         return;
  300.     }
  301.  
  302.     /* We're the kid */
  303.     if(ar_reading) {
  304.         dupto(pipe[WRITE],STDOUT,"(child) pipe to stdout");
  305.         ck_close(pipe[READ]);
  306.     } else {
  307.         dupto(pipe[READ],STDIN,"(child) pipe to stdin");
  308.         ck_close(pipe[WRITE]);
  309.     }
  310.  
  311.     /* We need a child tar only if
  312.        1: we're reading/writing stdin/out (to force reblocking)
  313.        2: the file is to be accessed by rmt (compress doesn't know how)
  314.        3: the file is not a plain file */
  315. #ifdef NO_REMOTE
  316.     if(!(ar_file[0]=='-' && ar_file[1]=='\0') && isfile(ar_file))
  317. #else
  318.     if(!(ar_file[0]=='-' && ar_file[1]=='\0') && !_remdev(ar_file) && isfile(ar_file))
  319. #endif
  320.     {
  321.         /* We don't need a child tar.  Open the archive */
  322.         if(ar_reading) {
  323.             archive=open(ar_file, O_RDONLY|O_BINARY, 0666);
  324.             if(archive<0) {
  325.                 msg_perror("can't open archive %s",ar_file);
  326.                 exit(EX_BADARCH);
  327.             }
  328.             dupto(archive,STDIN,"archive to stdin");
  329.             /* close(archive); */
  330.         } else {
  331.             archive=creat(ar_file,0666);
  332.             if(archive<0) {
  333.                 msg_perror("can't open archive %s",ar_file);
  334.                 exit(EX_BADARCH);
  335.             }
  336.             dupto(archive,STDOUT,"archive to stdout");
  337.             /* close(archive); */
  338.         }
  339.     } else {
  340.         /* We need a child tar */
  341.         ck_pipe(kidpipe);
  342.  
  343.         kidchildpid=fork();
  344.         if(kidchildpid<0) {
  345.             msg_perror("child can't fork");
  346.             exit(EX_SYSTEM);
  347.         }
  348.  
  349.         if(kidchildpid>0) {
  350.             /* About to exec compress:  set up the files */
  351.             if(ar_reading) {
  352.                 dupto(kidpipe[READ],STDIN,"((child)) pipe to stdin");
  353.                 ck_close(kidpipe[WRITE]);
  354.                 /* dup2(pipe[WRITE],STDOUT); */
  355.             } else {
  356.                 /* dup2(pipe[READ],STDIN); */
  357.                 dupto(kidpipe[WRITE],STDOUT,"((child)) pipe to stdout");
  358.                 ck_close(kidpipe[READ]);
  359.             }
  360.             /* ck_close(pipe[READ]); */
  361.             /* ck_close(pipe[WRITE]); */
  362.             /* ck_close(kidpipe[READ]);
  363.             ck_close(kidpipe[WRITE]); */
  364.         } else {
  365.         /* Grandchild.    Do the right thing, namely sit here and
  366.            read/write the archive, and feed stuff back to compress */
  367.             tar="tar (child)";
  368.             if(ar_reading) {
  369.                 dupto(kidpipe[WRITE],STDOUT,"[child] pipe to stdout");
  370.                 ck_close(kidpipe[READ]);
  371.             } else {
  372.                 dupto(kidpipe[READ],STDIN,"[child] pipe to stdin");
  373.                 ck_close(kidpipe[WRITE]);
  374.             }
  375.  
  376.             if (ar_file[0] == '-' && ar_file[1] == '\0') {
  377.                 if (ar_reading)
  378.                     archive = STDIN;
  379.                 else
  380.                     archive = STDOUT;
  381.             } else /* This can't happen if (ar_reading==2)
  382.                 archive = rmtopen(ar_file, O_RDWR|O_CREAT|O_BINARY, 0666);
  383.             else */if(ar_reading)
  384.                 archive = rmtopen(ar_file, O_RDONLY|O_BINARY, 0666);
  385.             else
  386.                 archive = rmtcreat(ar_file, 0666);
  387.  
  388.             if (archive < 0) {
  389.                 msg_perror("can't open archive %s",ar_file);
  390.                 exit(EX_BADARCH);
  391.             }
  392.  
  393.             if(ar_reading) {
  394.                 for(;;) {
  395.                     char *ptr;
  396.                     int max,count;
  397.  
  398.                     r_error_count = 0;
  399.                 error_loop:
  400.                     err=rmtread(archive, ar_block->charptr,(int)(blocksize));
  401.                     if(err<0) {
  402.                         readerror();
  403.                         goto error_loop;
  404.                     }
  405.                     if(err==0)
  406.                         break;
  407.                     ptr = ar_block->charptr;
  408.                     max = err;
  409.                     while(max) {
  410.                         count = (max<RECORDSIZE) ? max : RECORDSIZE;
  411.                         err=write(STDOUT,ptr,count);
  412.                         if(err!=count) {
  413.                             if(err<0) {
  414.                                 msg_perror("can't write to compress");
  415.                                 exit(EX_SYSTEM);
  416.                             } else
  417.                                 msg("write to compress short %d bytes",count-err);
  418.                             count = (err<0) ? 0 : err;
  419.                         }
  420.                         ptr+=count;
  421.                         max-=count;
  422.                     }
  423.                 }
  424.             } else {
  425.                 for(;;) {
  426.                     int n;
  427.                     char *ptr;
  428.  
  429.                     n=blocksize;
  430.                     ptr = ar_block->charptr;
  431.                     while(n) {
  432.                         err=read(STDIN,ptr,(n<RECORDSIZE) ? n : RECORDSIZE);
  433.                         if(err<=0)
  434.                             break;
  435.                         n-=err;
  436.                         ptr+=err;
  437.                     }
  438.                         /* EOF */
  439.                     if(err==0) {
  440.                         if(f_compress<2)
  441.                             blocksize-=n;
  442.                         else
  443.                             bzero(ar_block->charptr+n,blocksize-n,n);
  444.                         err=rmtwrite(archive,ar_block->charptr,blocksize);
  445.                         if(err!=(blocksize))
  446.                             writeerror(err);
  447.                         if(f_compress<2)
  448.                             blocksize+=n;
  449.                         break;
  450.                     }
  451.                     if(n) {
  452.                         msg_perror("can't read from compress");
  453.                         exit(EX_SYSTEM);
  454.                     }
  455.                     err=rmtwrite(archive, ar_block->charptr, (int)blocksize);
  456.                     if(err!=blocksize)
  457.                         writeerror(err);
  458.                 }
  459.             }
  460.  
  461.             /* close_archive(); */
  462.             exit(0);
  463.         }
  464.     }
  465.         /* So we should exec compress (-d) */
  466.     if(ar_reading)
  467.         execlp("compress", "compress", "-d", (char *)0);
  468.     else
  469.         execlp("compress", "compress", (char *)0);
  470.     msg_perror("can't exec compress");
  471.     _exit(EX_SYSTEM);
  472. }
  473.  
  474.  
  475. /* return non-zero if p is the name of a directory */
  476. isfile(p)
  477. char *p;
  478. {
  479.     struct stat stbuf;
  480.  
  481.     if(stat(p,&stbuf)<0)
  482.         return 1;
  483.     if((stbuf.st_mode&S_IFMT)==S_IFREG)
  484.         return 1;
  485.     return 0;
  486. }
  487.  
  488. #endif
  489.  
  490. /*
  491.  * Open an archive file.  The argument specifies whether we are
  492.  * reading or writing.
  493.  */
  494. /* JF if the arg is 2, open for reading and writing. */
  495. open_archive(reading)
  496.     int reading;
  497. {
  498.     msg_file = f_exstdout ? stderr : stdout;
  499.  
  500.     if (blocksize == 0) {
  501.         msg("invalid value for blocksize");
  502.         exit(EX_ARGSBAD);
  503.     }
  504.  
  505.     if(ar_file==0) {
  506.         msg("No archive name given, what should I do?");
  507.         exit(EX_BADARCH);
  508.     }
  509.  
  510.     /*NOSTRICT*/
  511.     if(f_multivol) {
  512.         ar_block = (union record *) valloc((unsigned)(blocksize+(2*RECORDSIZE)));
  513.         if(ar_block)
  514.             ar_block += 2;
  515.     } else
  516.         ar_block = (union record *) valloc((unsigned)blocksize);
  517.     if (!ar_block) {
  518.         msg("could not allocate memory for blocking factor %d",
  519.             blocking);
  520.         exit(EX_ARGSBAD);
  521.     }
  522.  
  523.     ar_record = ar_block;
  524.     ar_last   = ar_block + blocking;
  525.     ar_reading = reading;
  526.  
  527.     if (f_compress) {
  528.         if(reading==2 || f_verify) {
  529.             msg("cannot update or verify compressed archives");
  530.             exit(EX_ARGSBAD);
  531.         }
  532.         child_open();
  533.         if(!reading && ar_file[0]=='-' && ar_file[1]=='\0')
  534.             msg_file = stderr;
  535.         /* child_open(rem_host, rem_file); */
  536.     } else if (ar_file[0] == '-' && ar_file[1] == '\0') {
  537.         f_reblock++;    /* Could be a pipe, be safe */
  538.         if(f_verify) {
  539.             msg("can't verify stdin/stdout archive");
  540.             exit(EX_ARGSBAD);
  541.         }
  542.         if(reading==2) {
  543.             archive=STDIN;
  544.             msg_file=stderr;
  545.             write_archive_to_stdout++;
  546.         } else if (reading)
  547.             archive = STDIN;
  548.         else {
  549.             archive = STDOUT;
  550.             msg_file = stderr;
  551.         }
  552.     } else if (reading==2 || f_verify) {
  553.         archive = rmtopen(ar_file, O_RDWR|O_CREAT|O_BINARY, 0666);
  554.     } else if(reading) {
  555.         archive = rmtopen(ar_file, O_RDONLY|O_BINARY, 0666);
  556.     } else {
  557.         archive = rmtcreat(ar_file, 0666);
  558.     }
  559.     if(!_isrmt(archive)) {
  560.         struct stat tmp_stat;
  561.  
  562.         fstat(archive,&tmp_stat);
  563.         if((tmp_stat.st_mode&S_IFMT)==S_IFREG) {
  564.             ar_dev=tmp_stat.st_dev;
  565.             ar_ino=tmp_stat.st_ino;
  566.         }
  567.     }
  568.  
  569.     if (archive < 0) {
  570.         msg_perror("can't open %s",ar_file);
  571.         exit(EX_BADARCH);
  572.     }
  573. #ifdef    MSDOS
  574.     setmode(archive, O_BINARY);
  575. #endif
  576.  
  577.     if (reading) {
  578.         ar_last = ar_block;        /* Set up for 1st block = # 0 */
  579.         (void) findrec();               /* Read it in, check for EOF */
  580.  
  581.         if(f_volhdr) {
  582.             union record *head;
  583.             char *ptr;
  584.  
  585.             if(f_multivol) {
  586.                 ptr=malloc(strlen(f_volhdr)+20);
  587.                 sprintf(ptr,"%s Volume %d",f_volhdr,1);
  588.             } else
  589.                 ptr=f_volhdr;
  590.             head=findrec();
  591.             if(!head)
  592.                 exit(EX_BADARCH);
  593.             if(strcmp(ptr,head->header.name)) {
  594.                 msg("Volume mismatch!  %s!=%s\n",ptr,head->header.name);
  595.                 exit(EX_BADARCH);
  596.             }
  597.             if(ptr!=f_volhdr)
  598.                 free(ptr);
  599.         }
  600.     } else if(f_volhdr) {
  601.         bzero((void *)ar_block,RECORDSIZE);
  602.         if(f_multivol)
  603.             sprintf(ar_block->header.name,"%s Volume 1",f_volhdr);
  604.         else
  605.             strcpy(ar_block->header.name,f_volhdr);
  606.         ar_block->header.linkflag = LF_VOLHDR;
  607.         to_oct(time(0), 1+12, ar_block->header.mtime);
  608.         finish_header(ar_block);
  609.         /* ar_record++; */
  610.     }
  611. }
  612.  
  613.  
  614. /*
  615.  * Remember a union record * as pointing to something that we
  616.  * need to keep when reading onward in the file.  Only one such
  617.  * thing can be remembered at once, and it only works when reading
  618.  * an archive.
  619.  *
  620.  * We calculate "offset" then add it because some compilers end up
  621.  * adding (baserec+ar_record), doing a 9-bit shift of baserec, then
  622.  * subtracting ar_block from that, shifting it back, losing the top 9 bits.
  623.  */
  624. saverec(pointer)
  625.     union record **pointer;
  626. {
  627.     long offset;
  628.  
  629.     save_rec = pointer;
  630.     offset = ar_record - ar_block;
  631.     saved_recno = baserec + offset;
  632. }
  633.  
  634. /*
  635.  * Perform a write to flush the buffer.
  636.  */
  637.  
  638. /*send_buffer_to_file();
  639.   if(new_volume) {
  640.     deal_with_new_volume_stuff();
  641.     send_buffer_to_file();
  642.   }
  643.  */
  644.  
  645. fl_write()
  646. {
  647.     int err;
  648.     int copy_back;
  649. #ifdef TEST
  650.     static long test_written = 0;
  651. #endif
  652.  
  653. #ifdef TEST
  654.     if(test_written>=30720) {
  655.         errno = ENOSPC;
  656.         err = 0;
  657.     } else
  658. #endif
  659.     err = rmtwrite(archive, ar_block->charptr,(int) blocksize);
  660.     if(err!=blocksize && !f_multivol)
  661.         writeerror(err);
  662.  
  663. #ifdef TEST
  664.     if(err>0)
  665.         test_written+=err;
  666. #endif
  667.     if (err == blocksize) {
  668.         if(f_multivol) {
  669.             if(!save_name) {
  670.                 real_s_name[0]='\0';
  671.                 real_s_totsize=0;
  672.                 real_s_sizeleft = 0;
  673.                 return;
  674.             }
  675. #ifdef MSDOS
  676.             if(save_name[1]==':')
  677.                 save_name+=2;
  678. #endif
  679.             while(*save_name=='/')
  680.                 save_name++;
  681.  
  682.             strcpy(real_s_name,save_name);
  683.             real_s_totsize = save_totsize;
  684.             real_s_sizeleft = save_sizeleft;
  685.         }
  686.         return;
  687.     }
  688.  
  689.     /* We're multivol  Panic if we didn't get the right kind of response */
  690.     /* ENXIO is for the UNIX PC */
  691.     if(err>0 || (err<0 && errno!=ENOSPC && errno!=EIO && errno!=ENXIO))
  692.         writeerror(err);
  693.  
  694.     if(new_volume(0)<0)
  695.         return;
  696. #ifdef TEST
  697.     test_written=0;
  698. #endif
  699.     if(f_volhdr && real_s_name[0]) {
  700.         copy_back=2;
  701.         ar_block-=2;
  702.     } else if(f_volhdr || real_s_name[0]) {
  703.         copy_back = 1;
  704.         ar_block--;
  705.     } else
  706.         copy_back = 0;
  707.     if(f_volhdr) {
  708.         bzero((void *)ar_block,RECORDSIZE);
  709.         sprintf(ar_block->header.name,"%s Volume %d",f_volhdr,volno);
  710.         to_oct(time(0), 1+12, ar_block->header.mtime);
  711.         ar_block->header.linkflag = LF_VOLHDR;
  712.         finish_header(ar_block);
  713.     }
  714.     if(real_s_name[0]) {
  715.         int tmp;
  716.  
  717.         if(f_volhdr)
  718.             ar_block++;
  719.         bzero((void *)ar_block,RECORDSIZE);
  720.         strcpy(ar_block->header.name,real_s_name);
  721.         ar_block->header.linkflag = LF_MULTIVOL;
  722.         to_oct((long)real_s_sizeleft,1+12,
  723.                ar_block->header.size);
  724.         to_oct((long)real_s_totsize-real_s_sizeleft,
  725.                1+12,ar_block->header.offset);
  726.         tmp=f_verbose;
  727.         f_verbose=0;
  728.         finish_header(ar_block);
  729.         f_verbose=tmp;
  730.         if(f_volhdr)
  731.             ar_block--;
  732.     }
  733.  
  734.     err = rmtwrite(archive, ar_block->charptr,(int) blocksize);
  735.     if(err!=blocksize)
  736.         writeerror(err);
  737.  
  738. #ifdef TEST
  739.     test_written = blocksize;
  740. #endif
  741.     if(copy_back) {
  742.         ar_block+=copy_back;
  743.         bcopy((void *)(ar_block+blocking-copy_back),
  744.               (void *)ar_record,
  745.               copy_back*RECORDSIZE);
  746.         ar_record+=copy_back;
  747.  
  748.         if(real_s_sizeleft>=copy_back*RECORDSIZE)
  749.             real_s_sizeleft-=copy_back*RECORDSIZE;
  750.         else if((real_s_sizeleft+RECORDSIZE-1)/RECORDSIZE<=copy_back)
  751.             real_s_name[0] = '\0';
  752.         else {
  753. #ifdef MSDOS
  754.             if(save_name[1]==':')
  755.                 save_name+=2;
  756. #endif
  757.             while(*save_name=='/')
  758.                 save_name++;
  759.  
  760.             strcpy(real_s_name,save_name);
  761.             real_s_sizeleft = save_sizeleft;
  762.             real_s_totsize=save_totsize;
  763.         }
  764.         copy_back = 0;
  765.     }
  766. }
  767.  
  768. /* Handle write errors on the archive.    Write errors are always fatal */
  769. /* Hitting the end of a volume does not cause a write error unless the write
  770. *  was the first block of the volume */
  771.  
  772. void
  773. writeerror(err)
  774. int err;
  775. {
  776.     if (err < 0) {
  777.         msg_perror("can't write to %s",ar_file);
  778.         exit(EX_BADARCH);
  779.     } else {
  780.         msg("only wrote %u of %u bytes to %s",err,blocksize,ar_file);
  781.         exit(EX_BADARCH);
  782.     }
  783. }
  784.  
  785. /*
  786.  * Handle read errors on the archive.
  787.  *
  788.  * If the read should be retried, readerror() returns to the caller.
  789.  */
  790. void
  791. readerror()
  792. {
  793. #    define    READ_ERROR_MAX    10
  794.  
  795.     read_error_flag++;        /* Tell callers */
  796.  
  797.     msg_perror("read error on %s",ar_file);
  798.  
  799.     if (baserec == 0) {
  800.         /* First block of tape.  Probably stupidity error */
  801.         exit(EX_BADARCH);
  802.     }
  803.  
  804.     /*
  805.      * Read error in mid archive.  We retry up to READ_ERROR_MAX times
  806.      * and then give up on reading the archive.  We set read_error_flag
  807.      * for our callers, so they can cope if they want.
  808.      */
  809.     if (r_error_count++ > READ_ERROR_MAX) {
  810.         msg("Too many errors, quitting.");
  811.         exit(EX_BADARCH);
  812.     }
  813.     return;
  814. }
  815.  
  816.  
  817. /*
  818.  * Perform a read to flush the buffer.
  819.  */
  820. fl_read()
  821. {
  822.     int err;        /* Result from system call */
  823.     int left;        /* Bytes left */
  824.     char *more;        /* Pointer to next byte to read */
  825.  
  826.     /*
  827.      * Clear the count of errors.  This only applies to a single
  828.      * call to fl_read.  We leave read_error_flag alone; it is
  829.      * only turned off by higher level software.
  830.      */
  831.     r_error_count = 0;    /* Clear error count */
  832.  
  833.     /*
  834.      * If we are about to wipe out a record that
  835.      * somebody needs to keep, copy it out to a holding
  836.      * area and adjust somebody's pointer to it.
  837.      */
  838.     if (save_rec &&
  839.         *save_rec >= ar_record &&
  840.         *save_rec < ar_last) {
  841.         record_save_area = **save_rec;
  842.         *save_rec = &record_save_area;
  843.     }
  844.     if(write_archive_to_stdout && baserec!=0) {
  845.         err=rmtwrite(1, ar_block->charptr, blocksize);
  846.         if(err!=blocksize)
  847.             writeerror(err);
  848.     }
  849.     if(f_multivol) {
  850.         if(save_name) {
  851.             if(save_name!=real_s_name) {
  852. #ifdef MSDOS
  853.                 if(save_name[1]==':')
  854.                     save_name+=2;
  855. #endif
  856.                 while(*save_name=='/')
  857.                     save_name++;
  858.  
  859.                 strcpy(real_s_name,save_name);
  860.                 save_name=real_s_name;
  861.             }
  862.             real_s_totsize = save_totsize;
  863.             real_s_sizeleft = save_sizeleft;
  864.  
  865.         } else {
  866.             real_s_name[0]='\0';
  867.             real_s_totsize=0;
  868.             real_s_sizeleft = 0;
  869.         }
  870.     }
  871.  
  872. error_loop:
  873.     err = rmtread(archive, ar_block->charptr, (int)blocksize);
  874.     if (err == blocksize)
  875.         return;
  876.  
  877.     if((err == 0 || (err<0 && errno==ENOSPC)) && f_multivol) {
  878.         union record *head;
  879.  
  880.     try_volume:
  881.         if(new_volume((cmd_mode==CMD_APPEND || cmd_mode==CMD_CAT || cmd_mode==CMD_UPDATE) ? 2 : 1)<0)
  882.             return;
  883.     vol_error:
  884.         err = rmtread(archive, ar_block->charptr,(int) blocksize);
  885.         if(err < 0) {
  886.             readerror();
  887.             goto vol_error;
  888.         }
  889.         if(err!=blocksize)
  890.             goto short_read;
  891.  
  892.         head=ar_block;
  893.  
  894.         if(head->header.linkflag==LF_VOLHDR) {
  895.             if(f_volhdr) {
  896.                 char *ptr;
  897.  
  898.                 ptr=(char *)malloc(strlen(f_volhdr)+20);
  899.                 sprintf(ptr,"%s Volume %d",f_volhdr,volno);
  900.                 if(strcmp(ptr,head->header.name)) {
  901.                     msg("Volume mismatch! %s!=%s\n",ptr,head->header.name);
  902.                     --volno;
  903.                     free(ptr);
  904.                     goto try_volume;
  905.                 }
  906.                 free(ptr);
  907.             }
  908.             if(f_verbose)
  909.                 fprintf(msg_file,"Reading %s\n",head->header.name);
  910.             head++;
  911.         } else if(f_volhdr) {
  912.             msg("Warning:  No volume header!");
  913.         }
  914.  
  915.         if(real_s_name[0]) {
  916.             long from_oct();
  917.  
  918.             if(head->header.linkflag!=LF_MULTIVOL || strcmp(head->header.name,real_s_name)) {
  919.                 msg("%s is not continued on this volume!",real_s_name);
  920.                 --volno;
  921.                 goto try_volume;
  922.             }
  923.             if(real_s_totsize!=from_oct(1+12,head->header.size)+from_oct(1+12,head->header.offset)) {
  924.                 msg("%s is the wrong size (%ld!=%ld+%ld)",
  925.                        head->header.name,save_totsize,
  926.                        from_oct(1+12,head->header.size),
  927.                        from_oct(1+12,head->header.offset));
  928.                 --volno;
  929.                 goto try_volume;
  930.             }
  931.             if(real_s_totsize-real_s_sizeleft!=from_oct(1+12,head->header.offset)) {
  932.                 msg("This volume is out of sequence");
  933.                 --volno;
  934.                 goto try_volume;
  935.             }
  936.             head++;
  937.         }
  938.         ar_record=head;
  939.         return;
  940.     } else if (err < 0) {
  941.         readerror();
  942.         goto error_loop;    /* Try again */
  943.     }
  944.  
  945.  short_read:
  946.     more = ar_block->charptr + err;
  947.     left = blocksize - err;
  948.  
  949. again:
  950.     if (0 == (((unsigned)left) % RECORDSIZE)) {
  951.         /* FIXME, for size=0, multi vol support */
  952.         /* On the first block, warn about the problem */
  953.         if (!f_reblock && baserec == 0 && f_verbose && err > 0) {
  954.         /*    msg("Blocksize = %d record%s",
  955.                 err / RECORDSIZE, (err > RECORDSIZE)? "s": "");*/
  956.             msg("Blocksize = %d records", err / RECORDSIZE);
  957.         }
  958.         ar_last = ar_block + ((unsigned)(blocksize - left))/RECORDSIZE;
  959.         return;
  960.     }
  961.     if (f_reblock) {
  962.         /*
  963.          * User warned us about this.  Fix up.
  964.          */
  965.         if (left > 0) {
  966. error2loop:
  967.             err = rmtread(archive, more, (int)left);
  968.             if (err < 0) {
  969.                 readerror();
  970.                 goto error2loop;    /* Try again */
  971.             }
  972.             if (err == 0) {
  973.                 msg("archive %s EOF not on block boundary",ar_file);
  974.                 exit(EX_BADARCH);
  975.             }
  976.             left -= err;
  977.             more += err;
  978.             goto again;
  979.         }
  980.     } else {
  981.         msg("only read %d bytes from archive %s",err,ar_file);
  982.         exit(EX_BADARCH);
  983.     }
  984. }
  985.  
  986.  
  987. /*
  988.  * Flush the current buffer to/from the archive.
  989.  */
  990. flush_archive()
  991. {
  992.     int c;
  993.  
  994.     baserec += ar_last - ar_block;    /* Keep track of block #s */
  995.     ar_record = ar_block;        /* Restore pointer to start */
  996.     ar_last = ar_block + blocking;    /* Restore pointer to end */
  997.  
  998.     if (ar_reading) {
  999.         if(time_to_start_writing) {
  1000.             time_to_start_writing=0;
  1001.             ar_reading=0;
  1002.  
  1003.             if(file_to_switch_to>=0) {
  1004.                 if((c=rmtclose(archive))<0)
  1005.                     msg_perror("Warning: can't close %s(%d,%d)",ar_file,archive,c);
  1006.  
  1007.                 archive=file_to_switch_to;
  1008.             } else
  1009.                 (void)backspace_output();
  1010.             fl_write();
  1011.         } else
  1012.             fl_read();
  1013.     } else {
  1014.         fl_write();
  1015.     }
  1016. }
  1017.  
  1018. /* Backspace the archive descriptor by one blocks worth.
  1019.    If its a tape, MTIOCTOP will work.  If its something else,
  1020.    we try to seek on it.  If we can't seek, we lose! */
  1021. backspace_output()
  1022. {
  1023.     long cur;
  1024.     /* int er; */
  1025.     extern char *output_start;
  1026.  
  1027. #ifdef MTIOCTOP
  1028.     struct mtop t;
  1029.  
  1030.     t.mt_op = MTBSR;
  1031.     t.mt_count = 1;
  1032.     if((rmtioctl(archive,MTIOCTOP,&t))>=0)
  1033.         return 1;
  1034.     if(errno==EIO && (rmtioctl(archive,MTIOCTOP,&t))>=0)
  1035.         return 1;
  1036. #endif
  1037.  
  1038.         cur=rmtlseek(archive,0L,1);
  1039.     cur-=blocksize;
  1040.     /* Seek back to the beginning of this block and
  1041.        start writing there. */
  1042.  
  1043.     if(rmtlseek(archive,cur,0)!=cur) {
  1044.         /* Lseek failed.  Try a different method */
  1045.         msg("Couldn't backspace archive file.  It may be unreadable without -i.");
  1046.         /* Replace the first part of the block with nulls */
  1047.         if(ar_block->charptr!=output_start)
  1048.             bzero(ar_block->charptr,output_start-ar_block->charptr);
  1049.         return 2;
  1050.     }
  1051.     return 3;
  1052. }
  1053.  
  1054.  
  1055. /*
  1056.  * Close the archive file.
  1057.  */
  1058. close_archive()
  1059. {
  1060.     int child;
  1061.     int status;
  1062.     int c;
  1063.  
  1064.     if (time_to_start_writing || !ar_reading)
  1065.         flush_archive();
  1066.     if(cmd_mode==CMD_DELETE) {
  1067.         long pos;
  1068.  
  1069.         pos = rmtlseek(archive,0L,1);
  1070. #ifndef MSDOS
  1071.         /* FIXME does ftruncate really take an INT?! */
  1072.         (void) ftruncate(archive,(int)pos);
  1073. #else
  1074.         (void)rmtwrite(archive,"",0);
  1075. #endif
  1076.     }
  1077.     if(f_verify)
  1078.         verify_volume();
  1079.  
  1080.     if((c=rmtclose(archive))<0)
  1081.         msg_perror("Warning: can't close %s(%d,%d)",ar_file,archive,c);
  1082.  
  1083. #ifndef MSDOS
  1084.     if (childpid) {
  1085.         /*
  1086.          * Loop waiting for the right child to die, or for
  1087.          * no more kids.
  1088.          */
  1089.         while (((child = wait(&status)) != childpid) && child != -1)
  1090.             ;
  1091.  
  1092.         if (child != -1) {
  1093.             switch (TERM_SIGNAL(status)) {
  1094.             case 0:
  1095.                 /* Child voluntarily terminated  -- but why? */
  1096.                 if (TERM_VALUE(status) == MAGIC_STAT) {
  1097.                     exit(EX_SYSTEM);/* Child had trouble */
  1098.                 }
  1099.                 if (TERM_VALUE(status) == (SIGPIPE + 128)) {
  1100.                     /*
  1101.                      * /bin/sh returns this if its child
  1102.                      * dies with SIGPIPE.  'Sok.
  1103.                      */
  1104.                     break;
  1105.                 } else if (TERM_VALUE(status))
  1106.                     msg("child returned status %d",
  1107.                         TERM_VALUE(status));
  1108.             case SIGPIPE:
  1109.                 break;        /* This is OK. */
  1110.  
  1111.             default:
  1112.                 msg("child died with signal %d%s",
  1113.                  TERM_SIGNAL(status),
  1114.                  TERM_COREDUMP(status)? " (core dumped)": "");
  1115.             }
  1116.         }
  1117.     }
  1118. #endif    /* MSDOS */
  1119. }
  1120.  
  1121.  
  1122. #ifdef DONTDEF
  1123. /*
  1124.  * Message management.
  1125.  *
  1126.  * anno writes a message prefix on stream (eg stdout, stderr).
  1127.  *
  1128.  * The specified prefix is normally output followed by a colon and a space.
  1129.  * However, if other command line options are set, more output can come
  1130.  * out, such as the record # within the archive.
  1131.  *
  1132.  * If the specified prefix is NULL, no output is produced unless the
  1133.  * command line option(s) are set.
  1134.  *
  1135.  * If the third argument is 1, the "saved" record # is used; if 0, the
  1136.  * "current" record # is used.
  1137.  */
  1138. void
  1139. anno(stream, prefix, savedp)
  1140.     FILE    *stream;
  1141.     char    *prefix;
  1142.     int    savedp;
  1143. {
  1144. #    define    MAXANNO 50
  1145.     char    buffer[MAXANNO];    /* Holds annorecment */
  1146. #    define    ANNOWIDTH 13
  1147.     int    space;
  1148.     long    offset;
  1149.     int    save_e;
  1150.  
  1151.     save_e=errno;
  1152.     /* Make sure previous output gets out in sequence */
  1153.     if (stream == stderr)
  1154.         fflush(stdout);
  1155.     if (f_sayblock) {
  1156.         if (prefix) {
  1157.             fputs(prefix, stream);
  1158.             putc(' ', stream);
  1159.         }
  1160.         offset = ar_record - ar_block;
  1161.         (void) sprintf(buffer, "rec %d: ",
  1162.             savedp? saved_recno:
  1163.                 baserec + offset);
  1164.         fputs(buffer, stream);
  1165.         space = ANNOWIDTH - strlen(buffer);
  1166.         if (space > 0) {
  1167.             fprintf(stream, "%*s", space, "");
  1168.         }
  1169.     } else if (prefix) {
  1170.         fputs(prefix, stream);
  1171.         fputs(": ", stream);
  1172.     }
  1173.     errno=save_e;
  1174. }
  1175. #endif
  1176.  
  1177. /* We've hit the end of the old volume.  Close it and open the next one */
  1178. /* Values for type:  0: writing  1: reading  2: updating */
  1179. new_volume(type)
  1180. int    type;
  1181. {
  1182.     int    c;
  1183.     char    inbuf[80];
  1184.     char    *p;
  1185.     static FILE *read_file = 0;
  1186.     extern int now_verifying;
  1187.     extern char TTY_NAME[];
  1188.     char *getenv();
  1189.  
  1190.     if(!read_file && !f_run_script_at_end)
  1191.         read_file = (archive==0) ? fopen(TTY_NAME, "r") : stdin;
  1192.  
  1193.     if(now_verifying)
  1194.         return -1;
  1195.     if(f_verify)
  1196.         verify_volume();
  1197.     if((c=rmtclose(archive))<0)
  1198.         msg_perror("Warning: can't close %s(%d,%d)",ar_file,archive,c);
  1199.  
  1200.     volno++;
  1201.  tryagain:
  1202.     if (f_run_script_at_end)
  1203.         system(info_script);
  1204.     else for(;;) {
  1205.         fprintf(msg_file,"Prepare volume #%d and hit return: ",volno);
  1206.         if(fgets(inbuf,sizeof(inbuf),read_file)==0 || inbuf[0]=='\n')
  1207.             break;
  1208.         switch(inbuf[0]) {
  1209.         case '?':
  1210.         {
  1211.             fprintf(msg_file,"\
  1212.  n [name]   Give a new filename for the next (and subsequent) volume(s)\n\
  1213.  q        Abort tar\n\
  1214.  !        Spawn a subshell\n\
  1215.  ?        Print this list\n");
  1216.         }
  1217.             break;
  1218.  
  1219.         case 'q':       /* Quit */
  1220.             fprintf(msg_file,"No new volume; exiting.\n");
  1221.             if(cmd_mode!=CMD_EXTRACT && cmd_mode!=CMD_LIST && cmd_mode!=CMD_DIFF)
  1222.                 msg("Warning:  Archive is INCOMPLETE!");
  1223.             exit(EX_BADARCH);
  1224.  
  1225.         case 'n':       /* Get new file name */
  1226.         {
  1227.             char *q,*r;
  1228.             static char *old_name;
  1229.  
  1230.             for(q= &inbuf[1];*q==' ' || *q=='\t';q++)
  1231.                 ;
  1232.             for(r=q;*r;r++)
  1233.                 if(*r=='\n')
  1234.                     *r='\0';
  1235.             if(old_name)
  1236.                 free(old_name);
  1237.             old_name=p=(char *)malloc((unsigned)(strlen(q)+2));
  1238.             if(p==0) {
  1239.                 msg("Can't allocate memory for name");
  1240.                 exit(EX_SYSTEM);
  1241.             }
  1242.             (void) strcpy(p,q);
  1243.             ar_file=p;
  1244.         }
  1245.             break;
  1246.  
  1247.         case '!':
  1248. #ifdef MSDOS
  1249.             spawnl(P_WAIT,getenv("COMSPEC"),"-",0);
  1250. #else
  1251.                 /* JF this needs work! */
  1252.             switch(fork()) {
  1253.             case -1:
  1254.                 msg_perror("can't fork!");
  1255.                 break;
  1256.             case 0:
  1257.                 p=getenv("SHELL");
  1258.                 if(p==0) p="/bin/sh";
  1259.                 execlp(p,"-sh","-i",0);
  1260.                 msg_perror("can't exec a shell %s",p);
  1261.                 _exit(55);
  1262.             default:
  1263.                 wait(0);
  1264.                 break;
  1265.             }
  1266. #endif
  1267.             break;
  1268.         }
  1269.     }
  1270.  
  1271.     if(type==2 || f_verify)
  1272.         archive=rmtopen(ar_file,O_RDWR|O_CREAT,0666);
  1273.     else if(type==1)
  1274.         archive=rmtopen(ar_file,O_RDONLY,0666);
  1275.     else if(type==0)
  1276.         archive=rmtcreat(ar_file,0666);
  1277.     else
  1278.         archive= -1;
  1279.  
  1280.     if(archive<0) {
  1281.         msg_perror("can't open %s",ar_file);
  1282.         goto tryagain;
  1283.     }
  1284. #ifdef MSDOS
  1285.     setmode(archive,O_BINARY);
  1286. #endif
  1287.     return 0;
  1288. }
  1289.  
  1290. /* this is a useless function that takes a buffer returned by wantbytes
  1291.    and does nothing with it.  If the function called by wantbytes returns
  1292.    an error indicator (non-zero), this function is called for the rest of
  1293.    the file.
  1294.  */
  1295. int
  1296. no_op(size,data)
  1297. int size;
  1298. char *data;
  1299. {
  1300.     return 0;
  1301. }
  1302.  
  1303. /* Some other routine wants SIZE bytes in the archive.    For each chunk of
  1304.    the archive, call FUNC with the size of the chunk, and the address of
  1305.    the chunk it can work with.
  1306.  */
  1307. int
  1308. wantbytes(size,func)
  1309. long size;
  1310. int (*func)();
  1311. {
  1312.     char *data;
  1313.     long    data_size;
  1314.  
  1315.     while(size) {
  1316.         data = findrec()->charptr;
  1317.         if (data == NULL) {     /* Check it... */
  1318.             msg("Unexpected EOF on archive file");
  1319.             return -1;
  1320.         }
  1321.         data_size = endofrecs()->charptr - data;
  1322.         if(data_size>size)
  1323.             data_size=size;
  1324.         if((*func)(data_size,data))
  1325.             func=no_op;
  1326.         userec((union record *)(data + data_size - 1));
  1327.         size-=data_size;
  1328.     }
  1329.     return 0;
  1330. }
  1331.